import { sqlite, EnvConfig } from "websql-orm";
import { isDev } from "@/config/env";
import Friend from "./model/friend";
import Record from "./model/record";

class ChatDB {
	constructor() {
		EnvConfig.enableDebugLog = isDev;
		this.initTables();
	}
	openDb() {
		console.log('ChatDB');
		return openDatabase("chatDB", "1.0", "DB for chat", 2 * 1024 * 1024);
	}
	async createTable(table, fields = {}) {
		if (!table) {
			throw new Error("table is error");
		}
		const db = this.openDb();
		db.transaction(tx => {
			let fields_str = Object.entries(fields)
				.map(([k, v]) => {
					if (!v) {
						return k;
					}
					return `${k} ${v}`;
				})
				.join();
			tx.executeSql(`CREATE TABLE IF NOT EXISTS ${table} (${fields_str})`);
		});
	}

	initTables() {
		this.addFriend({ cr_id: 0 });
		this.addRecord({ ccr_id: 0 });
	}

	dropTable() {
		const db = this.openDb();
		db.transaction(tx => {
			tx.executeSql("DROP TABLE friend_list");
			tx.executeSql("DROP TABLE record_list");
		});
	}
	// 获取好友列表
	async getFriends() {
		const list = await sqlite.fromSql(
			new Friend(),
			"select * from friend where cr_id!=? order by updated_at desc",
			[0]
		);
		return list;
	}

	// 获取好友单条
	async getFriend(cr_id) {
		let info = await sqlite.fromSqlFirst(new Friend(), "select * from friend where cr_id=?", [
			cr_id
		]);
		return info;
	}
	// 更新好友单条
	async setFriend(data = {}) {
		let info = await this.getFriend(data.cr_id);
		if (!info) return;
		info = Object.assign(info, data);
		return info.save();
	}

	async putUnread(cr_id, { reset = false, updated = true }) {
		let info = await this.getFriend(cr_id);
		if (!info) return;
		if (reset) {
			info.unread_total = 0;
		} else {
			info.unread_total += 1;
		}
		if (updated) {
			info.updated_at = Date.now();
		}
		return info.save();
	}
	async putLastMsg(cr_id, msg = {}, updated = true) {
		let info = await this.getFriend(cr_id);
		if (!info) return;
		info.last_msg = msg.content;
		info.last_msg_type = msg.content_type;
		if (msg.created_at) {
			info.updated_at = msg.created_at * 1000;
		}
		console.log(msg, info);
		if (updated) {
			info.updated_at = Date.now();
		}
		return info.save();
	}
	// 更新好友列表数据
	setFriends(list) {
		list.forEach(async item => {
			let info = await this.getFriend(item.cr_id);
			if (!info) {
				let friend = new Friend();
				friend = Object.assign(friend, item);
				sqlite.insert(friend);
				return;
			}
		});
	}
	// 新增好友
	async addFriend(data) {
		let info = await this.getFriend(data.cr_id);
		if (!info) {
			let friend = new Friend();
			friend = Object.assign(friend, data);
			sqlite.insert(friend);
			return;
		}
	}
	// 清空表
	async clearTable() {
		return Promise.all([this.clearFriends(), this.clearRecords()]);
	}
	// 清除好友数据
	async clearFriends() {
		return sqlite.fromSql(new Friend(), "delete from friend", []);
	}
	// 清除聊天记录数据
	async clearRecords() {
		return sqlite.fromSql(new Record(), "delete from record", []);
	}

	async getRecord(ccr_id) {
		let info = await sqlite.fromSqlFirst(new Record(), "select * from record where ccr_id=?", [
			ccr_id
		]);
		return info;
	}
	setRecords(list) {
		list.forEach(async item => {
			let info = await this.getRecord(item.ccr_id);
			if (!info) {
				let record = new Record();
				record = Object.assign(record, item);
				sqlite.insert(record);
				return;
			}
		});
	}
	async addRecord(msg) {
		let info = await this.getRecord(msg.ccr_id);
		if (!info) {
			let record = new Record();
			record = Object.assign(record, msg);
			sqlite.insert(record);
			return;
		}
	}
}
export default new ChatDB();
